import { UserInfo } from "../type/login";
import { defineStore } from "pinia";
import { ref, watch } from "vue";
import router from "../router/index";
import loginService from "@/service/login.service";
import routes from "@/router/menuRoutes";
interface ApiInfo {
    name: string;
    method: string;
    api: string;
}

const useGlobalStore = defineStore("globalStore", () => {
    const token = ref();
    const setToken = (val: string) => {
        token.value = val;
    };
    const userInfo = ref<UserInfo>(new UserInfo());
    const setUserInfo = (val: UserInfo) => {
        userInfo.value = val;
    };

    const logOut = () => {
        token.value = "";
        userInfo.value = new UserInfo();
        expires_in.value = "";
        localStorage.removeItem("token");
        localStorage.removeItem("userInfo");
        localStorage.removeItem("expires_in");
        clearMenuRoutes();
        if (router.currentRoute.value.path != "/login") {
            router.replace("/login");
        }
    };

    const expires_in = ref<any>();
    const setExpires_in = (val: number) => {
        expires_in.value = val;
    };

    const menuRoutes = ref<any>();
    const getMenu = async () => {
        let res = await loginService.getMenu();
        let data = res.data.result.data;

        if (data) {
            menuRoutes.value = [...data];
            flatMenuRoutes(data);
            console.log(flatMenuRoutesMap.value, 777);
        }
    };

    const compareRoute = (obj: any) => {
        let res: any[] = [];
        let o: any;

        const compare = (arr: any[]) => {
            let parentPath = "";
            let node: any;
            let currentTree = [...arr];
            let tempArr: any = [];
            let flag = false;
            while ((node = currentTree.shift())) {
                node.parentPath = node.parentPath || parentPath;
                if (
                    node.path == obj.path &&
                    node.parentPath == obj.parentPath
                ) {
                    o = { ...node };
                    o.children = [];
                    flag = true;
                }

                if (
                    node.path != obj.path &&
                    node.path.startsWith(obj.path) &&
                    node.parentPath == obj.parentPath
                ) {
                    let ro = { ...node };
                    res.push(ro);
                }

                if (currentTree.length == 0 && flag == true) {
                    return;
                }

                node.children &&
                    tempArr.push(
                        ...node.children.map((item: any) => {
                            item.parentPath = node.parentPath
                                ? node.parentPath + "-" + item.path
                                : node.path;
                            return item;
                        }),
                    );

                if (currentTree.length == 0) {
                    currentTree.push(...tempArr);
                    tempArr = [];
                }
            }
        };
        compare(routes);

        return { res, o };
    };

    const authRoutes = ref();
    const generateRoutes = (arr: any[]) => {
        let res: any = [];
        if (arr) {
            const parse = (arr: any[], parentPath = "", res: any[]) => {
                for (let i = 0; i < arr.length; i++) {
                    let item = arr[i];
                    item.parentPath = parentPath;
                    let obj: any = compareRoute(item);
                    // console.log(item);
                    if (res.findIndex((r) => r.path == obj.o.path) == -1) {
                        res.push(obj.o);
                    }
                    if (!obj.o?.children) {
                        obj.o.children = [];
                    }
                    arr.push(...obj.res);

                    if (item.children) {
                        parse(
                            item.children,
                            parentPath
                                ? parentPath + "-" + item.path
                                : item.path,
                            obj.o.children,
                        );
                    }
                }
            };
            parse(arr, "", res);
        }

        // console.log(arr);

        // res.push(...whiteRoutes);

        authRoutes.value = res;

        return res;
    };

    const flatMenuRoutesMap = ref<Map<string, ApiInfo[]>>(new Map());
    const flatMenuRoutes = (menuRoutes: any[]) => {
        const parse = (arr: any[], parentPath: string = "") => {
            for (let i = 0; i < arr.length; i++) {
                let item = arr[i];
                if (item.apis && item.apis.length > 0) {
                    // let pp = parentPath.includes("/")
                    //     ? parentPath == "/"
                    //         ? ""
                    //         : parentPath
                    //     : "/" + parentPath;
                    let pp =
                        parentPath == ""
                            ? ""
                            : parentPath.includes("/")
                            ? parentPath
                            : "/" + parentPath;
                    let cp = item.path.includes("/")
                        ? item.path
                        : "/" + item.path;
                    let path = pp + cp;
                    flatMenuRoutesMap.value.set(
                        path,
                        item.apis.map((apiObj: any) => ({
                            method: apiObj.method,
                            api: apiObj.path,
                            name: apiObj.name,
                        })),
                    );
                } else {
                    if (item.children) {
                        parse(item.children, item.path);
                    }
                }
            }
        };
        parse([...menuRoutes]);
    };

    const authApis = ref<string[]>([]);
    const apisByPath = (path: string) => {
        if (flatMenuRoutesMap.value.has(path)) {
            let arr = flatMenuRoutesMap.value.get(path);
            if (arr) {
                authApis.value = arr.map(
                    (item) => item.method + "-" + item.api,
                );

                // console.log(authApis.value);
                return;
            }
        }
        authApis.value = [];
    };

    const clearMenuRoutes = () => {
        menuRoutes.value = undefined;
        authRoutes.value = undefined;
        flatMenuRoutesMap.value = new Map();
        authApis.value = [];
    };

    watch(
        () => router.currentRoute.value.path,
        (path) => {
            let key = path.replace(/\?.*/g, "");
            apisByPath(key);
        },
        {
            immediate: true,
        },
    );

    return {
        userInfo,
        setUserInfo,
        token,
        setToken,
        logOut,
        expires_in,
        setExpires_in,
        menuRoutes,
        authRoutes,
        generateRoutes,
        getMenu,
        authApis,
        apisByPath,
    };
});

export default useGlobalStore;
